package eai.tp2.lpco.web.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import eai.tp2.lpco.cameracatalog.ICameraCatalog;
import eai.tp2.lpco.database.DigitalCamera;
import eai.tp2.lpco.requests.IRequest;
import eai.tp2.lpco.web.beans.Camera;
import eai.tp2.lpco.web.beans.CameraList;
import eai.tp2.lpco.web.beans.ErrorList;
import eai.tp2.lpco.web.beans.ResultsBean;

/**
 * Servlet implementation class DatabaseCatalog
 */
public class DatabaseCatalog extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DatabaseCatalog() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String action = request.getParameter("do");		
		if(action.equals("detail")) {
			String name = request.getParameter("name");
			IRequest req = null;
			InitialContext ctx;
			try {
				ctx = new InitialContext();
				req = (IRequest) ctx.lookup("RequestBean/remote");
			} catch (NamingException e) {			
				String error;
				error = "Error while lookup for RequestBean:\n"+e.getMessage();
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}
			DigitalCamera temp = req.getCamera(name);			
			if(temp!=null) {
				Camera cam = new Camera();
				cam.setBrandName(temp.getBrandName());
				cam.setModelName(temp.getModelName());
				cam.setDate(temp.getDate());
				cam.setCameraId(temp.getCameraId());
				cam.setDescription(temp.getDescription());
				cam.setEffectivePixels(temp.getEffectivePixels());
				cam.setImageLink(temp.getImageLink());
				cam.setIsoRating(temp.getIsoRating());
				cam.setImageRatio(temp.getImageRatio());
				cam.setMaxRes(temp.getMaxRes());
				cam.setMinRes(temp.getMinRes());
				cam.setMaxShutter(temp.getMaxShutter());
				cam.setMinShutter(temp.getMinShutter());
				cam.setReviewLink(temp.getReviewLink());
				cam.setSensorSize(temp.getSensorSize());
				cam.setPrice(temp.getPrice());
				request.setAttribute("camera", cam);
				RequestDispatcher rd = request.getRequestDispatcher("camera_details.jsp");
				rd.forward(request, response);
			} else {
				String error;
				error = "Camera '"+name+"' doesn't exist.";
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}
		} else if(action.equals("list")) {
			IRequest req = null;
			InitialContext ctx;
			try {
				ctx = new InitialContext();
				req = (IRequest) ctx.lookup("RequestBean/remote");
			} catch (NamingException e) {			
				String error;
				error = "Error while lookup for RequestBean:\n"+e.getMessage();
				List<String> errors = new ArrayList<String>();
				errors.add(error);
				ErrorList list = new ErrorList();
				list.setErrorList(errors);		
				request.setAttribute("list", list);
				RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
				rd.forward(request, response);	
			}	
			List<String> list = req.getCameraNames();			
			CameraList bean = new CameraList();
			bean.setCameras(list);
			session.setAttribute("list", bean);
			response.sendRedirect("list.jsp");
		} else {
			//quer dizer que alguém andou a editar o link no browser 
			//error message
			String error;
			error = "Action not recognized.";
			List<String> errors = new ArrayList<String>();
			errors.add(error);
			ErrorList list = new ErrorList();
			list.setErrorList(errors);		
			request.setAttribute("list", list);
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);	
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		ICameraCatalog cameraCatalog = null;
		IRequest req = null;
		InitialContext ctx = null;
		try {
			ctx = new InitialContext();
			cameraCatalog = (ICameraCatalog) ctx.lookup("CameraCatalogBean/remote");
			req = (IRequest)ctx.lookup("RequestBean/remote");
		} catch (NamingException e) {			
			String error;
			error = "Error while lookup for CameraCatalogBean or RequestBean:\n"+e.getMessage();
			List<String> errors = new ArrayList<String>();
			errors.add(error);
			ErrorList list = new ErrorList();
			list.setErrorList(errors);		
			request.setAttribute("list", list);
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);	
		}		
		String[] checkboxValue = request.getParameterValues("camera_ckbox");
		if(checkboxValue!=null) {
			boolean addSomething = false;
			ResultsBean results = (ResultsBean) session.getAttribute("results");
			for (int i = 0; i < checkboxValue.length; i++) {
				String name = checkboxValue[i];
				if(req.getCamera(name)==null) {
					addSomething = true;
					DigitalCamera cam = results.getResult(name);					
					cameraCatalog.addDigitalCamera(cam);
					results.remove(checkboxValue[i]);					
				}
			}
			if(addSomething) {
				List<String> list = req.getCameraNames();			
				CameraList bean = new CameraList();
				bean.setCameras(list);
				session.setAttribute("list", bean);
			}
		}
		response.sendRedirect("search.jsp");
	}

}
